package com.icetec.iceintel.ui.activity;

import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.icetec.R;
import com.icetec.iceintel.framework.AppApplication;
import com.icetec.iceintel.framework.IceBaseActivity;
import com.icetec.iceintel.model.UserConfig;
import com.icetec.iceintel.netrequest.InstrutionSender;

import java.util.EventListener;

/**
 * 高级设置页面
 * 功能：路由网关手动配置
 *
 * Created by 坤道 on 2015/4/20.
 */

public class AdvancedSetupActivity extends IceBaseActivity{

    private final static String POINT = ".";
    private final static String PRE_ADDRESS = "192.168.1.1";
    private final static int MIN = 1;
    private final static int MAX = 255;



    private Switch manualSwitch;    //网关手动配置开关
    private RelativeLayout gatewayLayout;
    private EditText firstET;
    private EditText secondET;
    private EditText thirdET;
    private EditText fourthET;

    private String isManual;    //临时网关手动设置状态
    private String address;     //临时网关地址


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advancedsetup);

        manualSwitch = (Switch)this.findViewById(R.id.advancedSetup_manual_switch);
        gatewayLayout = (RelativeLayout)this.findViewById(R.id.advancedSetup_gateway_layout);
        firstET = (EditText)this.findViewById(R.id.advancedSetup_gateway_first_enter);
        secondET = (EditText)this.findViewById(R.id.advancedSetup_gateway_second_enter);
        thirdET = (EditText)this.findViewById(R.id.advancedSetup_gateway_third_enter);
        fourthET = (EditText)this.findViewById(R.id.advancedSetup_gateway_fourth_enter);

        this.findViewById(R.id.advancedSetup_layout).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                AdvancedSetupActivity.this.findViewById(R.id.advancedSetup_layout).setFocusable(true);
                AdvancedSetupActivity.this.findViewById(R.id.advancedSetup_layout).setFocusableInTouchMode(true);
                AdvancedSetupActivity.this.findViewById(R.id.advancedSetup_layout).requestFocus();
                HideKeyboard(v);
                return false;
            }
        });


        //设置软键盘回车按钮自动跳跃到下一个输入框
        firstET.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP){
                secondET.setFocusable(true);
                secondET.setFocusableInTouchMode(true);
                secondET.requestFocus();
                }
                return false;
            }
        });

        secondET.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP){
                    thirdET.setFocusable(true);
                    thirdET.setFocusableInTouchMode(true);
                    thirdET.requestFocus();
                }
                return false;
            }
        });

        thirdET.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP){
                    fourthET.setFocusable(true);
                    fourthET.setFocusableInTouchMode(true);
                    fourthET.requestFocus();
                }
                return false;
            }
        });


        //输入栏数字大小监听器定义
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };


        //设置Switch开关监听器
        manualSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    //若手动设置，则网关地址栏可见
                    Log.d("manualSwitch:", "listener");
                    gatewayLayout.setVisibility(View.VISIBLE);
                    isManual = UserConfig.isManual;

                    //将用户信息库里的网关地址赋值给网关地址栏
                    if(address == null){
                        address = AppApplication.getShareInstance().userConfig.getGatewayAddress() != null
                                ? AppApplication.getShareInstance().userConfig.getGatewayAddress() : PRE_ADDRESS;
                    }
                    Log.d("address", address);
                    String[] addresses = address.split("\\.");
                    Log.d("addresses", String.valueOf(addresses.length));
                    firstET.setText(addresses[0]);
                    secondET.setText(addresses[1]);
                    thirdET.setText(addresses[2]);
                    fourthET.setText(addresses[3]);
                }else{
                    //否则，则网关地址栏不可见
                    gatewayLayout.setVisibility(View.GONE);
                    isManual = UserConfig.notManual;
                }

            }
        });


        //获得用户高级设置配置信息
        isManual = AppApplication.getShareInstance().userConfig.getIsManualGatewaySetting() != null
                ? AppApplication.getShareInstance().userConfig.getIsManualGatewaySetting() : UserConfig.notManual;

        address = AppApplication.getShareInstance().userConfig.getGatewayAddress() != null
                ? AppApplication.getShareInstance().userConfig.getGatewayAddress() : PRE_ADDRESS;

        manualSwitch.setChecked(isManual.equals(UserConfig.isManual));
    }

    @Override
    public void finish() {
        AppApplication.getShareInstance().userConfig.setIsManualGatewaySetting(isManual);
        if(isManual.equals(UserConfig.isManual)){
            //将用户设置的网关转化为字符串
            StringBuffer addressBuffer = new StringBuffer();
            addressBuffer.append(firstET.getText());
            addressBuffer.append(POINT);
            addressBuffer.append(secondET.getText());
            addressBuffer.append(POINT);
            addressBuffer.append(thirdET.getText());
            addressBuffer.append(POINT);
            addressBuffer.append(fourthET.getText());
            //网关字符串
            address = addressBuffer.toString();
            AppApplication.getShareInstance().userConfig.setGatewayAddress(address);
            InstrutionSender.setGateWayIpAddress(AppApplication.getShareInstance().userConfig.getGatewayAddress());
            InstrutionSender.setIsGateWayConneted(true);
        }
        AppApplication.getShareInstance().savaUserConfig();
        setResult(AddDevicesActivity.ADVANCEDSETUP_REQUEST, getIntent());
        super.finish();
    }

    //隐藏虚拟键盘
    public static void HideKeyboard(View v)
    {
        InputMethodManager imm = ( InputMethodManager ) v.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE );
        if ( imm.isActive( ) ) {
            imm.hideSoftInputFromWindow( v.getApplicationWindowToken( ) , 0 );
        }
    }





    //返回键事件响应
    public void back(View view){
        this.finish();
    }



}
